package io.kiki.sba.registry.common.model.store;

import io.kiki.sba.registry.common.model.constants.ValueConstants;
import io.kiki.sba.registry.concurrent.ThreadLocalStringBuilder;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;

import java.io.Serializable;
import java.util.Objects;

@Setter
@Getter
public class DataInfo implements Serializable {

    /**
     * symbol :
     */
    public static final String DELIMITER = "#@#";
    public static final int DATAID_LENTH = 3;
    private String dataInfoId;
    private String instanceId;
    private String dataId;
    private String group;


    public DataInfo(String instanceId, String dataId, String group) {
        this.instanceId = instanceId;
        this.dataId = dataId;
        this.group = group;
        this.dataInfoId = toDataInfoId(instanceId, dataId, group);
    }


    public static String toDataInfoId(String instanceId, String dataId, String group) {
        if (dataId == null || dataId.isEmpty()) {
            throw new IllegalArgumentException("error dataId:" + dataId);
        }
        if (instanceId == null || instanceId.isEmpty()) {
            throw new IllegalArgumentException("error instanceId:" + instanceId);
        }
        if (group == null || group.isEmpty()) {
            throw new IllegalArgumentException("error group:" + group);
        }
        if (ValueConstants.DISABLE_DATA_ID_CASE_SENSITIVE) {
            dataId = dataId.toUpperCase();
        }
        return ThreadLocalStringBuilder.join(dataId, DELIMITER, instanceId, DELIMITER, group);
    }


    public static DataInfo valueOf(String dataInfoId) {
        String[] parts = parse(dataInfoId);
        return new DataInfo(parts[1], parts[0], parts[2]);
    }

    public static String[] parse(@NonNull String dataInfoId) {

        String[] str = dataInfoId.split(DELIMITER);
        if (str.length != DATAID_LENTH) {
            throw new IllegalArgumentException("dataInfoId input error!");
        }
        return str;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        DataInfo dataInfo = (DataInfo) o;
        return dataInfoId.equals(dataInfo.dataInfoId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(dataInfoId);
    }
}
